import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';

import '../entity/palette_model.dart';
import '../widgets/toast.dart';

class PaletteSettingPage extends StatefulWidget {
  final PaletteModel paletteModel;

  const PaletteSettingPage({super.key, required this.paletteModel});

  @override
  State<PaletteSettingPage> createState() => _PaletteSettingState();
}

class _PaletteSettingState extends State<PaletteSettingPage> {
  late final PaletteModel paletteModel;

  bool isEdit = false, deleteCheck = true;

  @override
  void initState() {
    paletteModel = widget.paletteModel;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, Object? result) async {
        if (!didPop) {
          Navigator.of(context).pop(isEdit ? paletteModel : null);
        }
      },
      child: Scaffold(
        appBar: AppBar(
          // 设置页标题
          title: Text(paletteModel.name),
          leading: IconButton(
            // 返回按钮
            icon: const Icon(Icons.arrow_back),
            // 返回到上一页
            onPressed: () async {
              Navigator.of(context).pop(isEdit ? paletteModel : null);
            },
          ),
          // 右上角按钮区域
          actions: [
            TextButton.icon(
              // icon: const Icon(Icons.edit),
              label: const Text('修改名称'),
              onPressed: () {
                _showEditPaletteNameDialog(context);
              },
            ),
            SizedBox(width: 10),
            TextButton.icon(
              // icon: const Icon(Icons.add),
              label: const Text('添加颜色'),
              onPressed: () {
                _showEditPaletteColorDialog(
                  context,
                  ColorItem(
                    name: '',
                    description: '',
                    view: true,
                    color: Colors.cyanAccent,
                  ),
                  true,
                );
              },
            ),
            SizedBox(width: 10),
          ],
        ),
        body: ListView(
          children: (paletteModel.data.isEmpty
              ? [
                  ListTile(
                    title: Text('无颜色'),
                    subtitle: Text('无颜色'),
                    onTap: () {},
                  ),
                ]
              : [
                  for (var colorItem in paletteModel.data)
                    Container(
                      color: colorItem.color,
                      child: ListTile(
                        title: Text(
                          colorItem.name,
                          style: TextStyle(
                            color: useWhiteForeground(colorItem.color)
                                ? Colors.white
                                : Colors.black,
                          ),
                        ),
                        subtitle: Text(
                          colorItem.description,
                          style: TextStyle(
                            color: useWhiteForeground(colorItem.color)
                                ? Colors.white
                                : Colors.black,
                          ),
                        ),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: Icon(
                                Icons.edit,
                                color: useWhiteForeground(colorItem.color)
                                    ? Colors.white
                                    : Colors.black,
                              ),
                              onPressed: () {
                                _showEditPaletteColorDialog(
                                  context,
                                  colorItem,
                                  false,
                                );
                              },
                            ),
                            // SizedBox(width: 10),
                            IconButton(
                              icon: Icon(
                                colorItem.view
                                    ? Icons.visibility
                                    : Icons.visibility_off,
                                color: useWhiteForeground(colorItem.color)
                                    ? Colors.white
                                    : Colors.black,
                              ),
                              onPressed: () {
                                setState(() {
                                  colorItem.view = !colorItem.view;
                                });
                                isEdit = true;
                              },
                            ),
                            // SizedBox(width: 10),
                            IconButton(
                              icon: Icon(
                                Icons.delete,
                                color: useWhiteForeground(colorItem.color)
                                    ? Colors.white
                                    : Colors.black,
                              ),
                              onPressed: () {
                                if (deleteCheck) {
                                  _showDeleteColorDialog(context, colorItem);
                                } else {
                                  setState(() {
                                    paletteModel.data.remove(colorItem);
                                  });
                                }
                              },
                            ),
                            // SizedBox(width: 10),
                          ],
                        ),
                      ),
                    ),
                ]),
        ),
      ),
    );
  }

  /// 显示修改调色板名称的对话框
  void _showEditPaletteNameDialog(BuildContext context) {
    TextEditingController controller = TextEditingController(
      text: paletteModel.name,
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('修改调色板名称'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(hintText: "请输入新的调色板名称"),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  paletteModel.name = controller.text;
                });
                if (paletteModel.data.isNotEmpty) {
                  isEdit = true;
                }
                Navigator.of(context).pop();
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  /// 调色板颜色编辑弹窗
  void _showEditPaletteColorDialog(
    BuildContext context,
    ColorItem colorItem,
    bool insert,
  ) {
    final nameController = TextEditingController(text: colorItem.name),
        descriptionController = TextEditingController(
          text: colorItem.description,
        );

    Color itemColor = colorItem.color;
    bool view = colorItem.view;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return AlertDialog(
              title: Text('${insert ? '新增' : '修改'}颜色'),
              content: SingleChildScrollView(
                child: Column(
                  children: [
                    ColorPicker(
                      pickerColor: itemColor,
                      onColorChanged: (Color color) {
                        // 更新颜色选择器内部状态
                        setState(() {
                          itemColor = color;
                        });
                        // 同时更新外层状态以刷新页面
                        this.setState(() {
                          // 外层状态更新，但不需要额外操作
                        });
                      },
                      colorPickerWidth: 300.0,
                      pickerAreaHeightPercent: 0.7,
                      enableAlpha: true,
                      displayThumbColor: true,
                      labelTypes: [],
                      paletteType: PaletteType.hsv,
                      pickerAreaBorderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(2.0),
                        topRight: Radius.circular(2.0),
                      ),
                      portraitOnly: true,
                    ),
                    SwitchListTile(
                      title: const Text('是否可见'),
                      value: view,
                      onChanged: (bool value) {
                        // 更新Switch内部状态
                        setState(() {
                          view = value;
                        });
                        // 同时更新外层状态
                        this.setState(() {
                          isEdit = true;
                        });
                      },
                    ),
                    TextField(
                      controller: nameController,
                      decoration: const InputDecoration(hintText: "名称(非必填)"),
                    ),
                    TextField(
                      controller: descriptionController,
                      decoration: const InputDecoration(hintText: "备注(非必填)"),
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    for (var item in paletteModel.data) {
                      if (item.color == itemColor && item != colorItem) {
                        var msg = item.name.isEmpty ? '' : "[${item.name}]";
                        Toast.show("该颜色已存在$msg", context);
                        return;
                      }
                    }
                    if (nameController.text.length > 10) {
                      Toast.show("名称最长10个字", this.context);
                      return;
                    }
                    colorItem.color = itemColor;
                    colorItem.view = view;
                    colorItem.name = nameController.text;
                    colorItem.description = descriptionController.text;
                    if (insert) {
                      paletteModel.data.insert(0, colorItem);
                    }
                    this.setState(() {
                      isEdit = true;
                    });
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  /// 删除Color弹窗
  void _showDeleteColorDialog(BuildContext context, ColorItem colorItem) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return AlertDialog(
              title: Text('删除此颜色?'),
              content: SingleChildScrollView(
                child: Column(
                  children: [
                    SwitchListTile(
                      title: const Text('退出此页面前不再提醒'),
                      value: !deleteCheck,
                      onChanged: (bool value) {
                        // 更新Switch内部状态
                        setState(() {
                          deleteCheck = !value;
                        });
                      },
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    this.setState(() {
                      paletteModel.data.remove(colorItem);
                    });
                    Navigator.of(context).pop();
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
